/**
 * 初始化项目插件的配置
 */

import Application from 'koa'
import bodyparser from 'koa-bodyparser'
import json from 'koa-json'
import logger from 'koa-logger'
import staticPublic from 'koa-static'
// @ts-ignore
import onerror from 'koa-onerror'
import config, { ConfigType } from '@/config'
import { DataSource } from "typeorm";
import { MysqlConnectionOptions } from "typeorm/driver/mysql/MysqlConnectionOptions";
import { join } from 'path';

export class Init {
    // 存放我们koa框架用到的所有插件
    private plugin: Array<Application.Middleware<Application.DefaultState & { },  Application.DefaultContext & {}>> = []
    protected koa: Application = new Application();
    protected config: ConfigType = <ConfigType><unknown>config;

    constructor() {
        this.initPlugin()
    }


    initPlugin() {
        onerror(this.koa)

        // 初始化 typeorm 的连接，并保存到全局变量 orm 中
        this.config.orm = new DataSource(<MysqlConnectionOptions>this.config.mysql)
        this.config.orm.initialize()
        
        // koa 的插件数据
        this.plugin = [
            bodyparser({
                enableTypes:['json', 'form', 'text']
            }),
            json(),
            // logger((str, args) => {
            //     console.log("str: ", str);
            //     console.log("args: ", args);
            // }),
            staticPublic(join(__dirname,config.staticPath))
        ]

        this.plugin.forEach(v => this.koa.use(v))
    }

}